import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import IScroll from '../../../assets/js/libs/iscroll';
import UpRefresh from '../../../assets/js/libs/uprefresh';
import { deepClone, localParam, lazyImg, preventBubble, handleAttrData, hanleClassifyData, setResetData } from '../../../assets/js/utils/index';
import  * as Request from '../../../services/search/index';
import config from '../../../assets/js/conf/config';
import SearchComponent from '../../../components/search/index';
import Css from '../../../assets/css/goods/search.css';

class GoodsSearch extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            showMask: false,
            bPriceMenu: false,
            bSaleMenu: false,
            showSearch: false,
            bScreen: '',
            productData: [],
            sKeywords: '',
            aPriceMin: 0,
            aPriceMax: 0,
            goodsNum: 0,
            aPriceOrder: [
                { title: '综合', type: 'all', checked: true },
                { title: '价格从底到高', type: 'up', checked: false },
                { title: '价格从高到底', type: 'down', checked: false },
            ],
            aClassify: {
                checked: true,
                items: []
            },
            aPrice: {
                checked: true,
                items: [
                    { price1: 1, price2: 50, checked: false },
                    { price1: 51, price2: 99, checked: false },
                    { price1: 100, price2: 300, checked: false },
                    { price1: 301, price2: 1000, checked: false },
                    { price1: 1001, price2: 9999, checked: false }
                ]
            },
            aGoodsAttr: []
        }
        this.myScroll = null;
        this.oUpRefresh = null;
        this.currentPage = 1;
        this.maxPage = 0;
        this.offsetBottom = 100;
        this.otype = 'all';
        this.sKeywords = '';
        this.bPriceMenu = false;
        this.bSaleMenu = false;
        this.cid = '';
        this.params = [];
    }

    componentDidMount(){
        this.sKeywords = decodeURIComponent(localParam(this.props.location.search).search.keywords);
        this.setState({ sKeywords: this.sKeywords });
        this.handleScroll();
        this.eventScroll();
        this.getProductData();
        this.getClassifyData();
        this.getGoodsParam(this.sKeywords);
    }

    componentWillUnmount(){
        //页面卸载时，重写setState,避免内存溢出
        this.setState = (state, callback) => {
            return ;
        }
    }

    //禁止滚动事件
    handleScroll(){
        this.refs.mask.addEventListener('touchmove', function(e){
            e.preventDefault();
        }, false);
        this.refs.screen.addEventListener('touchmove', function(e){
            e.preventDefault();
        }, false);
    }

    //显示筛选界面
    showScreen(){
        this.setState({ showMask: true, bScreen: Css['move'] });
    }

    //隐藏筛选界面
    hideScreen(){
        this.setState({ showMask: false, bScreen: Css['unmove'] });
    }

    //加入Iscroll事件
    eventScroll(){
        this.myScroll = new IScroll('#screen', {
            scrollX: false,
            scrollY: true,
            preventDefault: false
        });
    }

    //页面回退
    back(){
        this.props.history.goBack();
    }

    //显示隐藏综合排序
    handlePriceOrder(){
        this.bSaleMenu = false;
        this.setState({ bSaleMenu: false });
        if(!this.bPriceMenu){
            this.setState({ bPriceMenu: true });
        }else{
            this.setState({ bPriceMenu: false });
        }
    }

    //显示隐藏销量排序
    handleSalesOrder(){
        this.bPriceMenu = false;
        this.otype = 'sale';
        const bSaleMenuVisible = !this.bSaleMenu ? true : false;
        this.setState({ bPriceMenu: false });
        this.setState({ bSaleMenu: bSaleMenuVisible });
        this.getProductData();
    }

    //显示隐藏搜索组件
    displaySearch(){
        this.setState({ showSearch: !this.state.showSearch });
    }

    //获取商品数据
    getProductData(){
        const { aPriceMin, aPriceMax } = this.state;
        const priceMin = aPriceMin > 0 ? aPriceMin : '';
        const priceMax = aPriceMax > 0 ? aPriceMax : '';
        const aParams = this.params.length > 0 ? JSON.stringify(this.params) : '';
        const param = {
            keywords: this.sKeywords, param: aParams, page: 1, 
            price1: priceMin, price2: priceMax, otype: this.otype, cid: this.cid
        };
        Request.getProductData(param).then(res => {
            if(res.code === 200){
                this.setState({ productData: res.data, goodsNum: res.pageinfo.total }, () => {
                    lazyImg();
                });
                this.maxPage = res.pageinfo.pagenum;
                this.getScrollPage();
            }else{
                this.setState({ productData: [], goodsNum: 0 });
            }
        });
    }

    //获取分类数据
    getClassifyData(){
        Request.getClassifyData().then(res => {
            let aClassify = deepClone(this.state.aClassify);
            aClassify.items = res.code === 200 ? hanleClassifyData(res.data) : [];
            this.setState({ aClassify }, () => {
                this.myScroll.refresh();
            });
        })
    }

    //获取商品属性
    getGoodsParam(keywords){
        Request.getGoodsParam(keywords).then(res => {
            const aGoodsAttr = res.code === 200 ? handleAttrData(res.data, 'param') : [];
            this.setState({ aGoodsAttr });
        });
    }

    //滚动刷新商品数据
    getScrollPage(){
        const { aPriceMin, aPriceMax } = this.state;
        const priceMin = aPriceMin > 0 ? aPriceMin : '';
        const priceMax = aPriceMax > 0 ? aPriceMax : '';
        this.oUpRefresh = new UpRefresh({"curPage":this.currentPage,"maxPage":this.maxPage,
        "offsetBottom":this.offsetBottom}, curPage => {
            const param = {
                keywords: this.sKeywords, param: '', page: curPage, 
                price1: priceMin, price2: priceMax, otype: this.otype, cid: this.cid
            };
            Request.getProductData(param).then(res => {
                if(res.code === 200){
                    let aTempGoods = deepClone(this.state.productData);
                    aTempGoods = [...aTempGoods, ...res.data];
                    this.setState({ productData: aTempGoods }, () => { lazyImg(); });
                }
            });
        });
    }

    //选择价格排序
    checkedPriceOrder(e, index){
        e.stopPropagation();
        let aTempPriceOrder = deepClone(this.state.aPriceOrder);
        aTempPriceOrder.map(item => item.checked = false);
        aTempPriceOrder[index].checked = true;
        this.otype = aTempPriceOrder[index].type;
        this.setState({ aPriceOrder: aTempPriceOrder, bPriceMenu: false }, () => {
            this.getProductData();
        });
    }

    //本页面搜索关键词
    getChildkeywords(keywords){
        this.sKeywords = keywords;
        this.setState({ sKeywords: keywords, showSearch: false });
        this.props.history.replace(config.path+'goods/search?keywords='+keywords);
        this.setReset();
        this.getProductData();
        this.getGoodsParam(keywords);
    }

    //分类显示隐藏
    handleClassify(){
        let aClassify = deepClone(this.state.aClassify);
        const isChecked = aClassify.checked ? false : true;
        aClassify.checked = isChecked;
        this.setState({ aClassify });
    }

    //价格区间显示隐藏
    handlePrice(){
        let aPrice = deepClone(this.state.aPrice);
        const isChecked = aPrice.checked ? false : true;
        aPrice.checked = isChecked;
        this.setState({ aPrice });
    }

    //商品属性显示隐藏
    handleParam(index){
        let aGoodsAttr = deepClone(this.state.aGoodsAttr);
        const isChecked = aGoodsAttr[index].checked ? false : true;
        aGoodsAttr[index].checked = isChecked;
        this.setState({ aGoodsAttr });
    }

    //选择分类
    checkedClassify(index){
        let aClassify = deepClone(this.state.aClassify);
        aClassify.items.map((item, i) => {
            if(index !== i){ item.checked = false; }
        });
        if(aClassify.items[index].checked){
            aClassify.items[index].checked = false;
            this.cid = '';
        }else{
            aClassify.items[index].checked = true;
            this.cid = aClassify.items[index].cid;
        }
        this.setState({ aClassify });
    }

    //选择价格区间
    checkedPrice(index, minPrice, maxPrice){
        let aPrice = deepClone(this.state.aPrice);
        let aTempMin = minPrice, aTempMax = maxPrice;
        aPrice.items.map((item, i) => {
            if(index !== i){ item.checked = false; }
        });
        if(aPrice.items[index].checked){
            aPrice.items[index].checked = false;
            aTempMin = 0; aTempMax = 0;
        }else{
            aPrice.items[index].checked = true;
        }
        this.setState({ aPrice, aPriceMin: aTempMin, aPriceMax: aTempMax });
    }

    //选择商品属性
    checkedParam(attrIndex, paramIndex){
        let aGoodsAttr = deepClone(this.state.aGoodsAttr);
        const isChecked = aGoodsAttr[attrIndex].param[paramIndex].checked ? false : true;
        const pid = aGoodsAttr[attrIndex].param[paramIndex].pid;
        aGoodsAttr[attrIndex].param[paramIndex].checked = isChecked;
        if(isChecked){ 
            this.params.push(pid);
        }else{ 
            this.params = this.params.filter(item => item !== pid);
        }
        this.setState({ aGoodsAttr });
    }

    //点击确认搜索商品
    confirmSearch(){
        this.getProductData();
        this.hideScreen();
    }

    //全部重置
    setReset(){
        this.otype = 'all';
        this.cid = '';
        this.params = [];
        const { aClassify, aPrice, aGoodsAttr } = this.state;
        const aTempClassify = setResetData(deepClone(aClassify));
        const aTempPrice = setResetData(deepClone(aPrice));
        const aTempGoodsAttr = handleAttrData(deepClone(aGoodsAttr), 'param');
        this.setState({ 
            aPriceMin: 0, aPriceMax: 0, aClassify: aTempClassify, 
            aPrice: aTempPrice, aGoodsAttr: aTempGoodsAttr
        });
    }

    //页面跳转
    goPage(url){
        this.props.history.push(window.base.config.path+url);
    }

    render(){
        const { bScreen, showMask, bPriceMenu, bSaleMenu, showSearch, productData, 
            aPriceOrder, sKeywords, aClassify, aPrice, aPriceMin, aPriceMax, aGoodsAttr, goodsNum } = this.state;
        return (
            <div className={Css['search-page']}>
                <div className={Css['search-top']}>
                    <div className={Css['search-header']}>
                        <div className={Css['back']} onClick={() => this.back()}></div>
                        <div className={Css['search-wrap']} onClick={() => this.displaySearch()}>
                            <div className={Css['search-icon']}></div>
                            <div className={Css['search-text']}>{sKeywords}</div>
                        </div>
                        <div className={Css['search-btn']} onClick={() => this.showScreen()}>筛选</div>
                    </div>
                    <div className={Css['orders-main']}>
                        <div className={bPriceMenu ? Css['orders-item']+' '+Css['active'] : Css['orders-item']} onClick={() => this.handlePriceOrder()}>
                            <div className={Css['orders-text']}>综合</div>
                            <div className={Css['orders-icon']}></div>
                            <ul className={bPriceMenu ? Css['orders-menu'] : Css['orders-menu']+' hide'}>
                                {
                                    aPriceOrder.map((item,index) => {
                                        return (
                                            <li key={item.title} className={item.checked ? Css['active'] : ''} onClick={(e) => this.checkedPriceOrder(e, index)}>{item.title}</li>
                                        )
                                    }) 
                                }
                            </ul>
                        </div>
                        <div className={bSaleMenu ? Css['orders-item']+' '+Css['active'] : Css['orders-item']}  onClick={() => this.handleSalesOrder()}>
                            <div className={Css['orders-text']}>销量</div>
                        </div>
                    </div>
                </div>
                <div className={Css['goods-main']}>
                    { productData.length > 0 ? productData.map((product,index) => {
                        return (
                            <div key={index} className={Css['goods-list']} onClick={() => this.goPage('goods/details/item?gid='+product.gid)}>
                                <div className={Css['image']}><img src={require('../../../assets/images/common/lazyImg.jpg')} data-echo={product.image} alt={product.title} /></div>
                                <div className={Css['goods-content']}>
                                    <div className={Css['goods-title']}>{product.title}</div>
                                    <div className={Css['price']}>￥{product.price}</div>
                                    <div className={Css['sales']}>销量<span className={Css['sales-num']}>{product.sales}</span>件</div>
                                </div>
                            </div>
                        )
                    }) : <div className={Css['goods-empty']}>没有相关商品!</div> }
                </div>
                {/* 条件筛选页 */} 
                <div ref='mask' onClick={() => this.hideScreen()} className={showMask ? Css['mask'] : Css['mask']+' hide'}></div>
                <div ref='screen' id='screen' className={Css['screen']+' '+bScreen}>
                    <div>
                        {/* 分类 */}
                        <div className={Css['attr-wrap']}>
                            <div className={Css['attr-title-wrap']} onClick={() => this.handleClassify()}>
                                <div className={Css['attr-name']}>分类</div>
                                <div className={aClassify.checked ? Css['attr-icon'] : Css['attr-icon']+' '+Css['up']}></div>
                            </div>
                            <div className={aClassify.checked ? Css['item-wrap'] : Css['item-wrap']+' height-hide'}>
                                {
                                    aClassify.items.length > 0 ? aClassify.items.map((item, index) => {
                                        return (
                                            <div key={item.cid} className={item.checked ? Css['item']+' '+Css['active'] : Css['item']} onClick={() => this.checkedClassify(index)}>{item.title}</div>
                                        )
                                    }) : ''
                                }
                            </div>
                        </div>
                        <div style={{height:'1px',backgroundColor:'#EFEFEF'}}></div>
                        {/* 价格区间 */}
                        <div className={Css['attr-wrap']}>
                            <div className={Css['attr-title-wrap']} onClick={() => this.handlePrice()}>
                                <div className={Css['attr-name']}>价格区间</div>
                                <div className={Css['price-wrap']}>
                                    <div className={Css['price-input']}><input type='text' value={aPriceMin > 0 ? aPriceMin : ''} onChange={(e)=>this.setState({ aPriceMin: e.target.value.replace(/[a-zA-Z]|[\u4e00-\u9fa5]|[#|*|,|+|;]/g, '') })} onClick={(e)=>preventBubble(e)} placeholder="最低价" /></div>
                                    <div className={Css['price-line']}></div>
                                    <div className={Css['price-input']}><input type='text' value={aPriceMax > 0 ? aPriceMax : ''} onChange={(e)=>this.setState({ aPriceMax: e.target.value.replace(/[a-zA-Z]|[\u4e00-\u9fa5]|[#|*|,|+|;]/g, '') })} onClick={(e)=>preventBubble(e)} placeholder="最高价" /></div>
                                </div>
                                <div className={aPrice.checked ? Css['attr-icon'] : Css['attr-icon']+' '+Css['up']}></div>
                            </div>
                            <div className={aPrice.checked ? Css['item-wrap'] : Css['item-wrap']+' height-hide'}>
                                {
                                    aPrice.items.length > 0 ? aPrice.items.map((item, index) => {
                                        return (    
                                            <div key={item.price1} className={item.checked ? Css['item']+' '+Css['active'] : Css['item']} onClick={() => this.checkedPrice(index, item.price1, item.price2)}>{item.price1}-{item.price2}</div>
                                        )
                                    }) : ''
                                }
                            </div>
                        </div>
                        <div style={{height:'0.3rem',backgroundColor:'#EFEFEF'}}></div>
                        {
                            aGoodsAttr.length > 0 ? aGoodsAttr.map((item, index) => {
                                return (
                                    <React.Fragment key={item.attrid}>
                                        <div className={Css['attr-wrap']}>
                                            <div className={Css['attr-title-wrap']} onClick={() => this.handleParam(index)}>
                                                <div className={Css['attr-name']}>{item.title}</div>
                                                <div className={item.checked ? Css['attr-icon'] : Css['attr-icon']+' '+Css['up']}></div>
                                            </div>
                                            <div className={item.checked ? Css['item-wrap'] : Css['item-wrap']+' height-hide'}>
                                                {
                                                    item.param && item.param.length > 0 ? item.param.map((ktem, kndex) => {
                                                        return (
                                                            <div key={ktem.pid} className={ktem.checked ? Css['item']+' '+Css['active'] : Css['item']} onClick={() => this.checkedParam(index, kndex)}>{ktem.title}</div>
                                                        )
                                                    }) : ''
                                                }
                                            </div>
                                        </div>
                                        <div style={{height:'1px',backgroundColor:'#EFEFEF'}}></div>
                                    </React.Fragment>
                                )
                            }) : ''
                        }
                        <div className={Css['bottom-line']}></div>
                    </div>
                    <div className={Css['handle-wrap']}>
                        <div className={Css['item']}>共<span>{goodsNum}</span>件</div>
                        <div className={Css['item']+' '+Css['reset']} onClick={() => this.setReset()}>全部重置</div>
                        <div className={Css['item']+' '+Css['sure']} onClick={() => this.confirmSearch()}>确定</div>
                    </div>
                </div>
                 {/* 搜索组件 */}
                 {showSearch && <SearchComponent isLocal="1" childKeywords={(keywords) => this.getChildkeywords(keywords)} searchKeywords={sKeywords} closeSearch={() => this.displaySearch()}></SearchComponent>}
            </div>
        )
    }
}

export default connect((store) => {
    return store;
})(withRouter(GoodsSearch));
